<template>
  <div class="table-wrapper" v-loading="loading">
    <!-- height="400px"     日期  select 单机     input双击-->
    <el-scrollbar ref="scrollRef" @scroll="scrollFun">
      <!-- content: "";
            display: block;
            clear: both; float: left;width: 0-->

      <div class="scroolY" style="float: left; width: 0">
        <div class="merak_table edit_table" ref="editTableRef">
          <table class="scrollTable">
            <colgroup>
              <col width="50px" />
              <col v-if="selection" width="50px" />
              <col v-for="(column, cKey) in headers" :key="cKey" :width="`${column.width}px`" />
              <col width="100px" />
            </colgroup>
            <thead>
              <!-- <headerCell></headerCell> -->
              <tr class="thead-row">
                <th class="table-number table-fixed-column table-fixed-column-left table-cell-fixed" v-if="number">
                  <div class="opration-cell"></div>
                </th>
                <th class="table-checkbox table-fixed-column table-fixed-column-left table-cell-fixed" v-if="selection">
                  <qfCheckbox
                    :isChecked="allChecked"
                    :indeterminate="isIndeterminate"
                    @change.native.stop="allCheckedFun"
                  ></qfCheckbox>
                </th>
                <th
                  v-for="(column, cKey) in headers"
                  :key="cKey"
                  @mousedown.native.stop="startDrag(cKey)"
                  @click="e => acticeBgRow(e, column, cKey)"
                  :style="{ width: column.width }"
                  class="table-fixed-column"
                  :class="{ 'table-cell-fixed table-fixed-column-left': column.fixed == 'left' }"
                >
                  <div class="header-cell" :style="{ width: column.width }">
                    {{ column.title }}
                  </div>
                  <div class="cell-resizable" v-if="!!dragDrop && !(column.fixed == 'left')"></div>
                </th>
                <!-- //操作列 固定 -->
                <!-- table-cell-fixed-right table-box-shadow-right -->
                <th class="table-cell-fixed-right table-fixed-column-right" v-if="$slots.handle">
                  <!-- :style="{ width: handle.width }" -->
                  <div class="opration-cell">操作</div>
                </th>
              </tr>
            </thead>
            <tbody ref="tbodyRef" class="tbodyContent">
              <!-- <columnCell></columnCell> -->

              <tr
                v-for="(row, rsIndex) in columnsTableData"
                :key="rsIndex"
                class="tbody-row"
                :rowsIndex="row.index"
                :title="$t('merak.dobule_click_edit')"
              >
                <td class="table-cell table-number table-cell-fixed table-fixed-rows-left" v-if="number">
                  <!-- # xuliehao  -->
                  <div class="cell-nowrap">{{ row.index + 1 }}</div>
                </td>
                <td class="table-cell table-checkbox table-cell-fixed table-fixed-rows-left" v-if="selection">
                  <qfCheckbox :isChecked="row.selection" @change.native.stop="e => checkItemFun(e, rsIndex, row)"> </qfCheckbox>
                </td>
                <!-- 循环列      @dblclick.stop="column.data?.type=='input'?dbEditClick(column,row,rsIndex):''"
                            @click.stop="column.type=='input'?onceEditClick(column,row,rsIndex):''"-->
                <td
                  v-for="(column, rIndex) in headers"
                  :key="rIndex"
                  class="table-cell"
                  :class="{
                    'table-cell-fixed table-fixed-rows-left': column.fixed == 'left',
                    edit_disable: !column.isEdit,
                    'err-tip': !column.fixed && row[column.field]?.errTip
                  }"
                  @dblclick.stop="dbEditClick(column, row, rsIndex, rIndex, column.field)"
                  @click.stop="e => onceEditClick(e, column, row, rsIndex, rIndex, column.field)"
                >
                  <div
                    class="err-tip-triangle"
                    v-if="!column.fixed && row[column.field]?.errTip"
                    @click="e => errTipFun(e, row[column.field])"
                  ></div>
                  <div class="cell-nowrap" :class="{ 'select-nureal': column.type == 'select' && !row[column.field]?.isEdit }">
                    <slot
                      v-if="column.isEdit && row[column.field]?.isEdit"
                      :name="column.field"
                      :scope="{ [column.field]: row[column.field], index: row.index, key: column.field }"
                    >
                      <div v-if="column.type == 'input'">
                        <qfInput
                          v-model="row[column.field].value"
                          :maxlength="Number(column?.length)"
                          @change="value => editFormChange(value, column, row, 'input')"
                        ></qfInput>
                      </div>
                      <div v-if="column.type == 'number'">
                        <qfInput
                          v-number
                          v-model="row[column.field].value"
                          :maxlength="Number(column?.length)"
                          @change="value => editFormChange(value, column, row, 'input')"
                        ></qfInput>
                      </div>
                      <div v-if="column.type == 'select'">
                        <el-select
                          filterable
                          :multiple="column.multiple"
                          v-model="row[column.field].value"
                          @change="value => editFormChange(value, column, row, 'select')"
                        >
                          <el-option
                            v-for="selectItem in column.options"
                            :key="selectItem.value"
                            :label="selectItem.label"
                            :value="selectItem.value"
                          />
                        </el-select>
                      </div>
                      <div v-if="column.type == 'date'">
                        <!-- 时间 -->
                        <el-date-picker
                          :teleported="false"
                          v-model="row[column.field].value"
                          type="date"
                          value-format="YYYY-MM-DD"
                          @change="value => editFormChange(value, column, row, 'date')"
                        />
                        <!-- -->
                      </div>
                    </slot>

                    <span v-else :title="row[column.field]?.label">
                      {{ row[column.field]?.label }}
                    </span>
                  </div>
                </td>

                <!--   table-box-shadow-right v-if="handle.show"-->
                <td class="table-cell-fixed-right table-fixed-rows-right" v-if="$slots.handle">
                  <div class="cell-nowrap">
                    <slot name="handle" :row="row"></slot>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </el-scrollbar>

    <div class="error_div_tip">
      <div class="err_cont">
        <div class="tip_title">数据错误</div>
        <div class="errr_tip_content">
          <div class="err_tip_item"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { toRef, toRefs, ref, reactive, computed, watch, h, nextTick, onMounted, useSlots, onUnmounted, defineExpose } from "vue";
import qfCheckbox from "../a-qfCheckbox/index.vue";
import qfInput from "../a-qfInput/index.vue";
import { useGlobalStore } from "@/stores/modules/global";
import dayjs from "dayjs";
import useDateFormat from "@/hooks/useDateFormat";
import { json } from "stream/consumers";
import { columns } from "element-plus/es/components/table-v2/src/common";
const { format } = useDateFormat();
const globalStore = useGlobalStore();
const props = defineProps({
  //table 表格头部
  headData: {
    type: Array<any>,
    default: []
  },
  //table 表格数据
  tableData: {
    type: Array<any>,
    default: []
  },
  //table可编辑列类型   input双击 其余单击
  headConfig: {
    type: Object,
    default: {}
  },
  //是否可拖拽  默认显示
  dragDrop: {
    type: Boolean,
    default: true
  },
  //checkbox是否显示  默认不显示
  selection: {
    type: Boolean,
    default: false
  },
  //#虚列号是否显示  默认不显示
  number: {
    type: Boolean,
    default: true
  },
  //是否开启编辑 默认开启关闭虚拟
  editStatus: {
    type: Boolean,
    default: true
  },
  //开启虚拟加载后
  editStatusType: {
    type: Boolean,
    default: false
  }
});

console.log(props);
const disabled = ref(false);
const scrollRef = ref(null);
const scrollInnerRef = ref(null);
const editTableRef = ref(null);

//#region 滚动位置

//滚动到顶部
const initTopScroll = () => {
  scrollRef.value!.setScrollTop(0);
};
//滚动到底部
const initBottomScroll = () => {
  let clientHei = editTableRef.value!.clientHeight;
  // console.log(clientHei,"全部高度")
  scrollRef.value!.setScrollTop(clientHei);
};

//清空错误提示

const clearALLTip = params => {
  let subData = "";
  let tableData = JSON.parse(JSON.stringify(columnsTableData.value));
  if (params) {
    tableData = JSON.parse(JSON.stringify(params));
  }
  if (tableData.length) {
    subData = tableData.map(v => {
      v.errTip = "";
      return {
        ...itemObj
      };
    });
  }
  return subData;
};

//#endregion

// 获取插槽内容
let slots = useSlots();
// console.log(slots.handle)
// const headers = computed(() => {
//     let headArrNew = props.headData.map(headItem => {
//         let field = headItem.field;
//         let type = props.headConfig[field]?.type || props.headConfig[field];
//         let multiple = props.headConfig[field]?.multiple;

//         return {
//             ...headItem,
//             type: type,
//             isEdit: !!type,
//             multiple: !!multiple,
//             options: props.headConfig[field]?.options,
//             rowClass:false,//列颜色
//         }
//     })
//     return headArrNew;
// });
const headers = ref(null);
// fixedRowsColumns
watch(
  () => props.headData,
  (newValue, oldValue) => {
    console.log("监听值变化，，，，，", newValue);
    console.log(oldValue);
    let headArrNew = newValue.map(headItem => {
      let field = headItem.field;
      let type = props.headConfig[field]?.type || props.headConfig[field];
      let multiple = props.headConfig[field]?.multiple;

      return {
        ...headItem,
        type: type,
        isEdit: !!type,
        multiple: !!multiple,
        options: props.headConfig[field]?.options
      };
    });
    // console.log(headArrNew)
    headers.value = headArrNew;
    if (oldValue && newValue.length > oldValue.length) {
      fixedRowsColumns();
      sumWidth();
    }
  },
  { immediate: true, deep: true }
);

//#region emit监听事件
// emit
const emit = defineEmits<{
  changeSelection: [value: any]; //全选与反选
  editFormFun: [];
}>();
//#endregion

//#region table表格
const currentPage = ref(0); //当前页码
const total = ref(0); //总数据
const pageSize = ref(30); //每页展示多少条
const initDataBool = ref(true); //是否是第一次
const newTableDataArr = ref(null); //监听最新数据
const columnsTableData = ref(null); //最后展示数据
const rowItemNew = ref();
watch(
  () => props.tableData,
  (newValue, oldValue) => {
    console.log("监听值变化，，，，，", newValue);
    // console.log(oldValue)
    // if( rowItemNew.value){
    //     rowItemNew.value = "";//清空上次选中值
    // }

    if (props.editStatus) {
      //开启新增删除
      // let editArr = JSON.parse(JSON.stringify(newValue));
      // console.log(editArr)
      let editArrNew = newValue.map((editItem, index) => {
        return {
          ...editItem,
          index: index
        };
      });
      columnsTableData.value = editArrNew;
      console.log(columnsTableData.value);
      return;
    }
    newTableDataArr.value = newValue;

    //开启虚拟加载新增删除
    if (!initDataBool.value) {
      console.log("编辑触发");
      //不是第一次
      let allDataLen = newValue.length;
      let hei = allDataLen * 40;
      document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
      if (newValue.length > pageSize.value) {
        scrollDirection();
        return;
      }
      let editArr = JSON.parse(JSON.stringify(newValue));
      let editArrNew = editArr.map((editItem, index) => {
        return {
          ...editItem,
          index: index
        };
      });
      columnsTableData.value = JSON.parse(JSON.stringify(editArrNew));
    }

    if (oldValue && newValue.length > oldValue.length) {
      //新增
      initDataBool.value = false;
    }
  },
  { deep: true, immediate: true }
);

//#endregion

//#region 全选与反选
const isIndeterminate = ref(false);
const selectData = ref([]);
const allChecked = ref(false);

//全选
const allCheckedFun = e => {
  let checkBox = !allChecked.value;
  allChecked.value = checkBox; //全选
  isIndeterminate.value = false;
  columnsTableData.value = columnsTableData.value.map(tt => {
    return {
      ...tt,
      selection: checkBox
    };
  });
  if (checkBox) {
    //全部选中
    selectData.value = columnsTableData.value;
  } else {
    selectData.value = [];
  }

  //
  emit("changeSelection", selectData.value);
};

//反选
const checkItemFun = (e, rIndex, rItem) => {
  let selection = !rItem.selection;
  rItem.selection = selection;

  if (selection) {
    //选中塞值
    selectData.value.push(rItem); //当前选中列
  } else {
    //取消删除数组中
    let splitIndex = selectData.value.findIndex((value, index) => {
      return value.selection === false;
    });
    selectData.value.splice(splitIndex, 1);
  }
  isIndeterminate.value = true;

  //所有都选  选中   部分全选补选中
  if (selectData.value.length == columnsTableData.value.length) {
    allChecked.value = true;
    isIndeterminate.value = false;
  } else {
    allChecked.value = false;
    // isIndeterminate.value = false;
    if (selectData.value.length == 0) {
      isIndeterminate.value = false;
    }
  }
  emit("changeSelection", selectData.value);
};

//#endregion

// slots.handle

//#region 固定列
let widthArr = [];
const fixedRowsColumns = () => {
  widthArr = [];
  let theadDomArr = document.getElementsByClassName("table-fixed-column-left");
  // console.log(theadDomArr)
  let left = 0;
  for (let pp = 0; pp < theadDomArr.length; pp++) {
    let dom = theadDomArr[pp];
    dom.style.cssText = `left: ${left}px`;
    widthArr.push(left); //所有宽度集合在一个数组中

    let width = dom.getBoundingClientRect().width;
    left = left + width;
    // console.log(theadDomArr[pp].offsetWidth)
    // console.log(dom.getBoundingClientRect().width)
  }
  nextTick(() => {
    allTdLeft();
    if (slots.handle) {
      allTdRight();
    }
  });
};

const allTdLeft = () => {
  let trDom = document.getElementsByClassName("tbody-row");
  for (let trIndex = 0; trIndex < trDom.length; trIndex++) {
    //所有td添加left
    let tdDomArr = trDom[trIndex].children;
    for (let td = 0; td < tdDomArr.length; td++) {
      let tddom = tdDomArr[td];

      let tdIndexOf = tddom.className.indexOf("table-fixed-rows-left");
      if (tdIndexOf != -1) {
        tddom.style.cssText = `left: ${widthArr[td]}px`;
      }
    }
  }
};

//右侧添加阴影
const allTdRight = () => {
  const $firstEl = scrollRef.value.$el.firstElementChild;
  let scrollWidth = document.querySelector(".table-wrapper .scrollTable").scrollWidth;
  let theadDom = document.getElementsByClassName("thead-row"); //thead内容
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容

  if (scrollWidth - $firstEl.clientWidth > 0) {
    let thFixedRight = theadDom[0].getElementsByClassName("table-cell-fixed-right");
    //添加阴影
    thFixedRight[0].classList.add("table-box-shadow-right");

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加right
      let tdDomArr = tbodyDom[trIndex].getElementsByClassName("table-cell-fixed-right");
      let tddom = tdDomArr[0];
      tddom.classList.add("table-box-shadow-right");
    }
  }
};

const oprationDataFun = (num, type, offsetTop) => {
  // if(buulBool){
  // let num = 3;

  let oprationData = JSON.parse(JSON.stringify(columnsTableData.value)); //展示数组
  // console.log(oprationData)
  let tableAllLen = oprationData.length; //展示数组长度
  let laseIndex = oprationData[tableAllLen - 1].index; // 第一个索引

  // 向下加载
  if (type == "down") {
    // let lastIndex=oprationData[tableAllLen - 1+3].index;
    // console.log(laseIndex)
    // console.log(newTableDataArr.value.length,"==="+laseIndex)
    // console.log(newTableDataArr.value.slice(99, 103))
    let allHei = document.querySelector(".table-wrapper .scroolY").offsetHeight;
    let conHei = document.querySelector(".merak_table.edit_table").offsetHeight;
    // if(allHei-conHei==offsetTop){
    //     // 到达底部
    //     let bottomLen=newTableDataArr.value.length;
    //     let sliceIndex=bottomLen-pageSize.value-1;
    //     let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(sliceIndex, bottomLen)));
    //     let tableDataList = newTableData.map((tt, index) => {
    //         sliceIndex = sliceIndex + 1;
    //         return {
    //             ...tt,
    //             index: sliceIndex
    //         }

    //     })

    //     columnsTableData.value = tableDataList;
    //     return;
    // }
    if (newTableDataArr.value.length > laseIndex + num) {
      let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(laseIndex, laseIndex + num)));
      let tableDataList = newTableData.map((tt, index) => {
        return {
          ...tt,
          index: laseIndex
        };
      });
      oprationData.splice(0, num);
      columnsTableData.value = [...oprationData, ...tableDataList];
    } else {
      if (newTableDataArr.value.length == laseIndex) {
        return;
      }
      let otherLen = newTableDataArr.value.length - laseIndex;
      let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(laseIndex, laseIndex + otherLen)));
      let tableDataList = newTableData.map((tt, index) => {
        return {
          ...tt,
          index: laseIndex
        };
      });

      columnsTableData.value = [...oprationData, ...tableDataList];
    }
    return;
  }

  // 向上加载
  // slice(1,2)  取得是下标为1的数据 第二个

  let firstIndex = oprationData[0].index;
  console.log(firstIndex, "每次第一个");
  if (offsetTop == 0) {
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, pageSize.value)));
    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      return {
        ...tt,
        index: tIndex //firstIndex - sliceLen + tIndex
      };
    });
    columnsTableData.value = tableDataList;
    return;
  }
  if (firstIndex - num > 0) {
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(firstIndex - num - 1, firstIndex - 1)));

    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      // 11  14-3+0
      // 12  14-3+1
      // 13  14-3+2
      // 14
      return {
        ...tt,
        index: firstIndex - sliceLen + tIndex - 1
      };
    });
    oprationData.splice(tableAllLen - num, num);
    columnsTableData.value = [...tableDataList, ...oprationData];
  } else {
    console.log("=====chufa");
    if (firstIndex == 1) {
      return;
    }

    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, firstIndex - 1)));
    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      return {
        ...tt,
        index: firstIndex - sliceLen + tIndex - 1
      };
    });
    columnsTableData.value = [...tableDataList, ...oprationData];
  }
};

// 滚动
let beforeScrollHei = 0; //上一次滚动位置
let interval = null;
//节流数据 向上、向下
const throttle = directionType => {
  // console.log(beforeScrollHei, numCount + "上次滚动，，，" + scrollTopDiff)
  let scrollTop = document.querySelector(".table-wrapper .el-scrollbar__wrap").scrollTop;
  scrollDirection(directionType);
  if (scrollTop == beforeScrollHei) {
    clearInterval(interval);
    interval = null;
  }
};
//内容滚动到位置
const scrollDirection = () => {
  let oprationData = JSON.parse(JSON.stringify(columnsTableData.value)); //展示数组
  // console.log(oprationData)
  let oprationDataLen = oprationData.length; //展示数组长度

  let scrollTop = document.querySelector(".table-wrapper .el-scrollbar__wrap").scrollTop;
  let clientScrollHei = document.querySelector(".table-wrapper .el-scrollbar").scrollHeight; //滚动区域高度
  let scrollHeight = document.querySelector(".table-wrapper .scroolY").scrollHeight; //滚动所有高度
  let firstNum = Math.ceil(scrollTop / 42);

  if (scrollTop + clientScrollHei >= scrollHeight) {
    let laseIndex = oprationData[oprationDataLen - 1].index; // 当前数组的最后一个索引
    let tableAllLen = newTableDataArr.value.length;
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(tableAllLen - pageSize.value, tableAllLen)));
    let tableDataList = newTableData.map((tt, index) => {
      laseIndex = tableAllLen - newTableData.length + index;
      return {
        ...tt,
        index: laseIndex
      };
    });
    columnsTableData.value = tableDataList;
    return;
  }
  let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(firstNum, firstNum + pageSize.value)));
  let tableDataList = newTableData.map((tt, index) => {
    return {
      ...tt,
      index: firstNum + index
    };
  });
  columnsTableData.value = tableDataList;
};
const scrollFun = scrollVal => {
  //隐藏error错误
  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none;`;
  if (!props.editStatus) {
    //新增、删除禁止编辑
    // console.log(scrollVal)
    let maxHei = document.querySelector(".table-wrapper .scroolY").offsetHeight; //内容区域最大高度
    // console.log(maxHei, "内容区域最大高度")
    let clientScrollHei = document.querySelector(".table-wrapper .el-scrollbar").scrollHeight; //滚动区域高度
    // console.log(clientScrollHei, "滚动区域高度")
    let clientHei = document.querySelector(".table-wrapper .merak_table.edit_table").offsetHeight; //内容课时区域高度
    // console.log(clientHei, "内容课时区域高度")
    let diffHei = clientHei - clientScrollHei;
    // console.log(diffHei, "相差")
    let scrollTop = scrollVal.scrollTop;
    let alreadyScrollTop = scrollTop - diffHei; //上次滚动高度位置
    let scrollDirection = ""; //滚动位置方向
    if (scrollTop - beforeScrollHei > 0) {
      document.querySelector(".merak_table.edit_table").style.cssText = `margin-top: ${scrollTop - diffHei}px`;
      // document.querySelector(".merak_table.edit_table").style.cssText = `top: ${scrollTop-diffHei}px`;
    } else {
      // document.querySelector(".merak_table.edit_table").style.cssText = `top: ${scrollTop}px`;
      document.querySelector(".merak_table.edit_table").style.cssText = `margin-top: ${scrollTop}px`;
    }
    if (interval == null)
      // 未发起时，启动定时器，1秒1执行

      interval = setInterval(() => {
        throttle(scrollDirection);
      }, 500);
    beforeScrollHei = scrollTop;
  }

  // 左侧固定列

  let theadDom = document.getElementsByClassName("thead-row"); //thead内容
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容
  // thead 固定数量
  let thFixed = theadDom[0].getElementsByClassName("table-cell-fixed");
  if (thFixed.length > 0) {
    //没有固定列
    for (let thIndex = 0; thIndex < thFixed.length; thIndex++) {
      thFixed[thIndex].classList.add("table-box-shadow");
      if (scrollVal.scrollLeft == 0) {
        thFixed[thIndex].classList.remove("table-box-shadow");
      }
    }

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加left
      let tdDomArr = tbodyDom[trIndex].children;
      let tddom = tdDomArr[thFixed.length - 1];
      tddom.classList.add("table-box-shadow");
      if (scrollVal.scrollLeft == 0) {
        tddom.classList.remove("table-box-shadow");
      }
      // tddom.classList.add(boxShadowClassName);
      // tddom.setAttribute("class", boxShadowClassName);
      // let tdIndexOf = tddom.className.indexOf("table-fixed-rows-left");
    }
  }

  // 右侧固定列      if( slots.handle){
  if (scrollVal.scrollLeft > 0 && slots.handle) {
    const $firstEl = scrollRef.value.$el.firstElementChild;
    let offestWidth = $firstEl.scrollWidth - $firstEl.clientWidth - $firstEl.scrollLeft;
    let thFixedRight = theadDom[0].getElementsByClassName("table-cell-fixed-right");
    //添加阴影
    thFixedRight[0].classList.add("table-box-shadow-right");
    if (offestWidth <= 1) {
      // 允许1px的误差
      //滚动到右侧 移除阴影
      thFixedRight[0].classList.remove("table-box-shadow-right");
    }

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加right
      let tdDomArr = tbodyDom[trIndex].getElementsByClassName("table-cell-fixed-right");
      let tddom = tdDomArr[0];
      tddom.classList.add("table-box-shadow-right");
      if (offestWidth <= 1) {
        // 允许1px的误差
        tddom.classList.remove("table-box-shadow-right");
      }
    }
  }
};

//#endregion

//#region 表头点击事件

//#region 编辑事件 双击与单机
const tbodyRef = ref(null);

const rowIndexNew = ref();
const filedKeyNew = ref(""); //当前选中格子key
// 双击
const dbEditClick = (columnItem, rowItem, rowIndex, colIndex, filedKey) => {
  if (!columnItem.isEdit) {
    //不可编辑
    return;
  }
  if (columnItem.type == "input") {
    //恢复每行
    initEditRow();
    //td和th添加选中样式
    addTdClass(rowIndex, colIndex);
    rowIndexNew.value = rowIndex;
    rowItemNew.value = rowItem;
    filedKeyNew.value = filedKey;
    rowItem[columnItem.field].isEdit = true;
  }
  //隐藏error错误
  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none;`;
};
//单击
let rowCell = 0,
  colCell = 0,clickBool=false;
const onceEditClick = ($e, columnItem, rowItem, rowIndex, colIndex, filedKey) => {
  rowCell = rowIndex;
  colCell = colIndex;
  clickBool=true;
  // console.log(rowIndex,colIndex)
  // console.log(new Date().getTime(), "=======")
  // //如果当前行列是打开的
  // if (rowItem[columnItem.field].isEdit == true && columnItem.type == 'input') {
  //     return;
  // }
  // //恢复每行
  if (filedKeyNew.value != filedKey) {
    //点击不是同一行恢复
    initEditRow();
  }

  // //td和th添加选中样式
  addTdClass(rowIndex, colIndex);

  // //input为双击
  // //不可编辑
  if (!columnItem.isEdit || columnItem.type == "input") {
    // console.log("input为双击 不可编辑 ")
    return;
  }

  rowIndexNew.value = rowIndex;
  rowItemNew.value = rowItem;
  rowItem[columnItem.field].isEdit = true;
};

//错误提示
const errTipFun = ($e, rowItem) => {
  // console.log(rowItem.errTip)
  let left = $e.clientX,
    top = $e.clientY;
  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:block;left:${left + 2}px;top: ${top - 2}px`;
  document.querySelector(".err_tip_item").innerText = rowItem.errTip;
};
//td和th添加样式
let currTdDom = "";
const addTdClass = (rowIndex, colIndex) => {
  let cellIndex = colIndex;
  if (props.selection) {
    cellIndex = cellIndex + 1;
  }
  if (props.number) {
    cellIndex = cellIndex + 1;
  }

  let headCssActive = `.merak_table thead tr.thead-row>th:nth-child(${cellIndex + 1}){
            background-color:var(--el-color-primary-light-9);
            border-bottom:2px solid var(--el-color-primary);
            box-shadow:none;
        }`;
  let bodyTdCssActive = `
                .merak_table tbody tr.tbody-row:nth-child(${rowIndex + 1})>td:nth-child(1){
                    background-color:var(--el-color-primary-light-9);
                    border-right:2px solid var(--el-color-primary);
                }
               
                `;
  // let currActiveTd = ` .merak_table tbody tr:nth-child(${(rowIndex + 1)}) td:nth-child(${(cellIndex + 1)}){
  //             background-color:var(--el-color-primary-light-9);

  //         }`;
  mearkTable.innerHTML = headCssActive + bodyTdCssActive;
  //针对当前点击替换class
  if (currTdDom) {
    currTdDom.classList.remove("active-bg-row-td");
  }
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容
  let tddom = tbodyDom[rowIndex].getElementsByClassName("table-cell")[cellIndex];
  currTdDom = tddom;
  tddom.classList.add("active-bg-row-td");
};

//点击行列渲染样式

let mearkTable = document.createElement("style");
mearkTable.id = "markeId";
document.querySelector("body").appendChild(mearkTable);

const acticeBgRow = ($e, columnItem, columnIndex) => {
  //针对当前点击替换class
  if (currTdDom) {
    currTdDom.classList.remove("active-bg-row-td");
  }
  let cellIndex = columnIndex;
  if (props.selection) {
    cellIndex = cellIndex + 1;
  }
  if (props.number) {
    cellIndex = cellIndex + 1;
  }

  let headCssActive = `.merak_table thead tr.thead-row>th:nth-child(${cellIndex + 1}){
            background-color:var(--el-color-primary-light-9);
            border-bottom:2px solid var(--el-color-primary);
            box-shadow:none;
                }`;
  let bodyCssActive = ` .merak_table tbody tr.tbody-row>td:nth-child(${
    cellIndex + 1
  }){background-color:var(--el-color-primary-light-9);
                    border-left:2px solid var(--el-color-primary) ;border-right:2px solid var(--el-color-primary);
                    border-bottom: 1px solid var(--el-color-primary-light-8);
                    } 
              
                .merak_table tbody tr.tbody-row:last-child>td:nth-child(${cellIndex + 1}){
                    border-bottom:2px solid var(--el-color-primary)
                }
                `;
  mearkTable.innerHTML = bodyCssActive;
  setTimeout(() => {
    mearkTable.innerHTML = headCssActive + bodyCssActive;
  }, 48);
};

//表单事件
const editFormChange = (currVal, columnItem, rowItem, type) => {
  // console.log(columnItem)
  // console.log(rowItem)
  // console.log(type)
  let trIndex = rowItem.index; //当前数组中索引位置
  const field = columnItem.field;
  rowItem[field].value = currVal;
  delete rowItem[field].errTip; //删除错误提示
  if (type == "input") {
    rowItem[field].label = currVal;
    emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));

    return;
  }
  if (type == "select") {
    if (columnItem.options.length) {
      if (columnItem.multiple) {
        //多选
        const array_new = columnItem.options.filter(item => currVal.some(ele => ele == item.value));
        let labelArr = [];
        if (array_new.length) {
          array_new.map(newItem => {
            labelArr.push(newItem.label);
          });
          rowItem[field].label = labelArr.join(",");
        }
      } else {
        let optionsArr = columnItem.options.find(item => item.value == currVal);
        rowItem[field].label = optionsArr.label;
      }

      emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));
    }
    return;
  }

  if (type == "date") {
    rowItem[field].label =
      globalStore.language == "ru" ? dayjs(currVal).format("DD-MM-YYYY") : dayjs(currVal).format("YYYY-MM-DD");
    emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));
    // newTableDataArr.value.splice(trIndex,1,rowItem);//替换全部数组中的数据
    // console.log(newTableDataArr.value)
    // console.log( props.tableData)
    return;
  }
};

//重置滚动条
const resetScrollSet = () => {
  let newArr = newTableDataArr.value;
  if (!newArr) {
    newArr = columnsTableData.value;
  }
  let hei = newArr.length * 40;
  document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
};

//恢复每行
const ininBaseInfo = () => {
  if (rowItemNew.value) {
    rowItemNew.value = ""; //清空上次选中值
  }
};
const initEditRow = () => {
  if (rowItemNew.value) {
    //row有值替换上一行
    Object.keys(rowItemNew.value).map(key => {
      delete rowItemNew.value[key].isEdit;
    });
    //针对当前点击替换class
    if (currTdDom) {
      // console.log(currTdDom)
      currTdDom.classList.remove("active-bg-row-td");
    }
    mearkTable.innerHTML = "";
    columnsTableData.value.splice(rowIndexNew.value, 1, rowItemNew.value);
    rowItemNew.value = ""; //清空上次选中值
  }
};
//关闭编辑事件
const parentEditClose = event => {
  // document.querySelector("body").removeChild( document.getElementById("markeId"));
  const tbodyToHide = tbodyRef.value as HTMLElement;

  if (tbodyToHide && !tbodyToHide.contains(event.target as Node)) {
    //隐藏error错误
    document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none;`;
    // console.log("关闭编辑事件。。。。")
    //恢复每行
    initEditRow();
  }
};
//#endregion

//#region 拖拽
// 拖拽
const startDrag = columnIndex => {
  const startX = event.clientX;
  const startWidth = headers.value[columnIndex]?.width || 200;

  const handleDrag = event => {
    const currentX = event.clientX;
    const diffX = currentX - startX;
    headers.value[columnIndex].width = `${parseInt(startWidth, 10) + diffX}px`;
  };

  const stopDrag = () => {
    document.removeEventListener("mousemove", handleDrag);
    document.removeEventListener("mouseup", stopDrag);
  };

  document.addEventListener("mousemove", handleDrag);
  document.addEventListener("mouseup", stopDrag);
};
//#endregion

//提交表单数据
const submitData = params => {
  let subData = "";
  let tableData = JSON.parse(JSON.stringify(columnsTableData.value));
  if (params) {
    tableData = JSON.parse(JSON.stringify(params));
  }
  if (tableData.length) {
    subData = tableData.map(v => {
      let itemObj = {};
      delete v.index;
      delete v.isEdit;
      Object.keys(v).map(k => {
        itemObj[k] = typeof v[k].value == "string" ? v[k].value.trim() : v[k].value;
      });
      return {
        ...itemObj
      };
    });
  }
  return subData;
};

//计算第一页展示多少条
const sumCountShowTr = () => {
  let headHei = 40,
    tbodyTrHei = 40;

  if (props.editStatus) {
    //开启新增删除
    // columnsTableData.value =JSON.parse(JSON.stringify(newTableDataArr.value));
    loading.value = false;
    return;
  }
  let hei = newTableDataArr.value.length * tbodyTrHei;
  document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
  //当前table高度
  let tableBaseOtherHei = document.querySelector(".table-wrapper").offsetHeight;
  //   可绑定数据条数
  let maxNum = Math.ceil(tableBaseOtherHei / 40);
  pageSize.value = maxNum;
  // console.log(maxNum)0-14   14条
  let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, maxNum)));
  let tableDataList = newTableData.map((tt, index) => {
    let pindex = index;
    return {
      ...tt,
      index: pindex
    };
  });

  columnsTableData.value = tableDataList;

  loading.value = false;
};

//计算宽度
const sumWidth = () => {
  let clientAllWidth = Number(document.querySelector(".merak_table.edit_table").clientWidth) - 200;
  let width = clientAllWidth / headers.value.length;
  width = width < 200 ? 200 : width;
  let newHeader = JSON.parse(JSON.stringify(headers.value));
  let newHeaderArr = newHeader.map(h => {
    return {
      ...h,
      width: h.width ?? width
    };
  });
  console.log(newHeaderArr);
  headers.value = newHeaderArr;
};


//粘贴
const handlePaste = async event => {
  switch (event.keyCode) {
    case 86: //按键86就是粘贴事件
    if(clickBool==false) return false;
      const text = await navigator.clipboard?.readText(); 
      let arrTxt = text.split("\r\n");
      arrTxt = arrTxt.filter(a => a);
      // console.log(rowCell, colCell);

      let headersColumn = headers.value;
      let oprationArr = newTableDataArr.value || columnsTableData.value;

      if (arrTxt && arrTxt.length) {
        // 粘贴的有文字
        arrTxt.map((txtItem, tindex) => {
          let rowIndex = Number(rowCell) + tindex;
          if (rowIndex < oprationArr.length) {
            let oprationItem = JSON.parse(JSON.stringify(oprationArr[rowIndex]));

            let txtLineArr = txtItem.split("\t");
            txtLineArr.map((tline, lindex) => {
              let field = headersColumn[lindex + Number(colCell)]?.field;
              if (field) {
                oprationItem[field].label = tline;
                oprationItem[field].value = tline;
              }
            });
 
            // oprationArr.splice(rowIndex, 1, oprationItem);
             emit("editFormFun", JSON.parse(JSON.stringify(oprationItem)))
          }
        });
      }
      rowCell=0;colCell=0;clickBool=false;
      break;
  }
};

let timmer = new Date().getTime();
const loading = ref(true);
onMounted(() => {
  nextTick(() => {
    let now = new Date().getTime();

    sumCountShowTr();

    fixedRowsColumns();

    sumWidth();

    document.addEventListener("click", parentEditClose);

    window.addEventListener("keydown", handlePaste);
  });
});
onUnmounted(() => {
  console.log("卸载");
  // document.querySelector("body").removeChild(mearkTable);
  let markeId = document.getElementById("markeId");
  console.log(markeId);
  if (markeId) {
    document.querySelector("body").removeChild(markeId);
  }
  document.removeEventListener("click", parentEditClose);
});

// 暴露给父组件使用
defineExpose({ editTableRef, submitData, initBottomScroll, initTopScroll, ininBaseInfo, resetScrollSet, clearALLTip });
</script>

<style lang="scss">
@import url(./index.scss);
</style>
